package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shangyuapi/data_source"
	"shangyuapi/models"
	"shangyuapi/service"
)

type UserlistRBody struct {
	Data       []models.User `json:"data"`
	PageNo     int           `json:"pageNo"`
	PageSize   int           `json:"pageSize"`
	TotalCount int64         `json:"totalCount"`
	TotalPage  int64         `json:"totalPage"`
}

type UserlistBody struct {
	Uid      int    `json:"uid"`
	PageNo   int    `json:"pageNo"`
	Pagesize int    `json:"pagesize"`
	Name     string `json:"name"`
	Phone    string `json:"phone"`
	Shenhe   int64  `json:"shenhe" gorm:"shenhe"` //1未提交 2审核中 3审核通过 4审核失败
}

func Userlist(ctx *gin.Context) {
	request := UserlistBody{}
	ctx.ShouldBind(&request)
	phone := request.Phone
	currentPage := request.PageNo
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)

	var miyao string
	miyao = service.Miyao()
	key := []byte(miyao)
	phonejm, _ := service.Encrypt(key, phone)

	var count int64
	var users []models.User
	res := data_source.Db

	if phone != "" {
		res = res.Where("phone = ?", phonejm)
	}
	res.Model(&models.User{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)

	for k, v := range users {
		phone1, _ := service.Decrypt(key, v.Phone)
		users[k].Phone = phone1
	}
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := UserlistRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Userinfo(ctx *gin.Context) {
	request := UserlistBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	var users models.User
	data_source.Db.Where("id = ?", uid).First(&users)

	var miyao string
	miyao = service.Miyao()
	key := []byte(miyao)
	phone1, _ := service.Decrypt(key, users.Phone)
	users.Phone = phone1
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    users,
		"msg":     "ok",
	})
	return

}

func Usershenhe(ctx *gin.Context) {
	request := UserlistBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	shenhe := request.Shenhe
	var users models.User
	data_source.Db.Model(&models.User{}).Where("id = ?", uid).Update("shenhe", shenhe)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    users,
		"msg":     "ok",
	})
	return

}
